package com.qiaoyanqing.textdemoqyq7.Fragments;


import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.qiaoyanqing.textdemoqyq7.Activities.WebViewActivity;
import com.qiaoyanqing.textdemoqyq7.Adapters.BannerAdapter;
import com.qiaoyanqing.textdemoqyq7.Adapters.ToutiaolvAdapter;
import com.qiaoyanqing.textdemoqyq7.AsyncTasks.ToutiaoJsonAsynctTsk;
import com.qiaoyanqing.textdemoqyq7.AsyncTasks.VPAsyncTask;
import com.qiaoyanqing.textdemoqyq7.Beans.Baike;
import com.qiaoyanqing.textdemoqyq7.Beans.Toutiao;
import com.qiaoyanqing.textdemoqyq7.Beans.ViewpagerBean;
import com.qiaoyanqing.textdemoqyq7.CallBacks.ToutiaoCB;
import com.qiaoyanqing.textdemoqyq7.CallBacks.ViewPagerCB;
import com.qiaoyanqing.textdemoqyq7.R;
import com.qiaoyanqing.textdemoqyq7.SQL.MySQLiteopenHelper;
import com.qiaoyanqing.textdemoqyq7.Utils.HeadViewUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class ToutiaoFragment extends Fragment implements AbsListView.OnScrollListener, Handler.Callback, ViewPager.OnPageChangeListener, AdapterView.OnItemClickListener {
    private ListView mListview;
    private List<Baike> mData = new ArrayList<>();

    private MySQLiteopenHelper mHelper;

    // t头布局需要的元素
    private ViewPager mViewPager;
    private TextView mTextView;
    private LinearLayout mTabContainer;
    private BannerAdapter mBannerAdapter;
    private List<ViewpagerBean> mVPData = new ArrayList<>();
    private List<ImageView> mImageData = new ArrayList<>();
    private int currentPosition = Integer.MAX_VALUE / 2;
    private int lastIdex = Integer.MAX_VALUE %3;

    private static final String BASE_URL = "http://sns.maimaicha.com/api?apikey=b4f4ee31a8b9acc866ef2afb754c33e6&format=json&method=";
    //头条数据
    public static final String TOUTIAO_URL = BASE_URL + "news.getHeadlines";
    //首页幻灯片数据路径
    public static final String LUNBO_URL = BASE_URL + "news.getSlideshow";
    // 分页
    private static final String PAGE = "&page=";
    private Handler mHandler = new Handler((Handler.Callback) this);
    private ToutiaolvAdapter mToutiaolvAdapter;

    public ToutiaoFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_toutiao, container, false);
        mListview = (ListView) view.findViewById(R.id.toutiao_listview);
        mHelper=new MySQLiteopenHelper(getContext());

        //加载头布局数据
        initHeadData();
        //加载数据，从网络上获取的数据
        initData();

        initListview();
        //分页
        initPageChange();
        //设置条目点击事件
        initItemclick();



        return view;

    }

    private void initItemclick() {

        mListview.setOnItemClickListener(this);
    }

    private void initHeadData() {

        new VPAsyncTask(new ViewPagerCB() {
            @Override
            public void sendData(List<ViewpagerBean> data) {
                //数据加载回来了

                mVPData.addAll(data);

                Message message = Message.obtain();
                message.what = 1;
                message.obj = data;
                mHandler.sendMessage(message);
                initViewpager(data);

            }
        }).execute(LUNBO_URL);

    }


    private void initIndicator(List<ViewpagerBean> data, List<ImageView> Imagedata) {
        for (int i = 0; i < data.size(); i++) {
            View view = new View(getContext());
         //   view.setBackgroundResource(R.drawable.selected);
            view.setBackgroundResource(R.drawable.icon02);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            params.rightMargin = 10;
            view.setLayoutParams(params);
            mTabContainer.addView(view);
        }

        mTabContainer.getChildAt(Integer.MAX_VALUE /2);

         //这里显示第一个
          mTextView.setText(mVPData.get(0).getTitle());

    }


    private void initPageChange() {
        mListview.setOnScrollListener(this);

    }

    private void initListview() {
        mToutiaolvAdapter = new ToutiaolvAdapter(getContext(), mData);

        //以下是头布局
        View headview = LayoutInflater.from(getContext()).inflate(R.layout.headviewpager, mListview, false);
        mViewPager = (ViewPager) headview.findViewById(R.id.headviewpager);
        mTextView = (TextView) headview.findViewById(R.id.heartextview);
        mTabContainer = (LinearLayout) headview.findViewById(R.id.tabs);
        mBannerAdapter = new BannerAdapter(mImageData);
        mViewPager.setAdapter(mBannerAdapter);
        mViewPager.setCurrentItem(currentPosition);
        mViewPager.addOnPageChangeListener(this);




        mListview.addHeaderView(headview);
        mListview.setAdapter(mToutiaolvAdapter);
    }

    private void initData() {

        new ToutiaoJsonAsynctTsk(new ToutiaoCB() {
            @Override
            public void senddata(List<Baike> data) {

                mData.addAll(data);
                mToutiaolvAdapter.notifyDataSetChanged();
            }
        }).execute(TOUTIAO_URL+ PAGE + page);


    }

    private boolean istrue = false;
    private int page = 0;

    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {
        if (istrue && i == SCROLL_STATE_IDLE) {
            page++;
            initData();
        }

    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {
        if (i + i1 == i2) {
            istrue = true;
        } else {
            istrue = false;
        }

    }

    @Override
    public boolean handleMessage(Message message) {
        if (mHandler.hasMessages(2)) {
            mHandler.removeMessages(2);
        }
        switch (message.what) {

            case 1:
                List<ViewpagerBean> data = (List<ViewpagerBean>) message.obj;
                initIndicator(data, mImageData);
                initViewpager(data);
                break;
            case 2:

                currentPosition++;
               //文本改变
                mTextView.setText(mVPData.get(currentPosition%mVPData.size()).getTitle());

                mViewPager.setCurrentItem(currentPosition);
                mHandler.sendEmptyMessageDelayed(2, 3000);
                break;
            case 3:

                break;
            case 4:
                currentPosition = message.arg1;
                mHandler.sendEmptyMessageDelayed(2, 3000);
                break;

        }

        return false;
    }

    private void initViewpager(List<ViewpagerBean> list) {

        for (int i = 0; i < list.size(); i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            String path = list.get(i).getImage();
           //  String path=mVPData.get(i).getImage();
            String pathnotImpty="http://s1.sns.maimaicha.com/images/2015/12/29/20151229093519_45699_suolue3.jpg";
            Picasso.with(getContext()).load(path.length()!=0?path:pathnotImpty).into(imageView);
            mImageData.add(imageView);
        }
        mBannerAdapter.notifyDataSetChanged();
        mHandler.sendEmptyMessageDelayed(2, 3000);

    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
       //TODO 这里是轮播加小球，这里有问题
//         mTabContainer.getChildAt(lastIdex % mVPData.size()).setEnabled(true);
//         mTabContainer.getChildAt(position % mVPData.size()).setEnabled(false);
//         lastIdex = position % mImageData.size();
//        mTabContainer.getChildAt(lastIdex).setEnabled(true);


        mHandler.sendMessage(Message.obtain(mHandler, 4, position, 1));

    }


    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_DRAGGING:
                mHandler.sendEmptyMessage(3);
                break;

        }

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        SQLiteDatabase db=mHelper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("id",mData.get(i).getId());
        values.put("title",mData.get(i).getTitle());
        values.put("source",mData.get(i).getSource());
        values.put("create_time",mData.get(i).getCreate_time());
        db.insert("tea",null,values);
        Toast.makeText(getContext(), "加入到了浏览记录", Toast.LENGTH_SHORT).show();

        Intent intent=new Intent(getContext(), WebViewActivity.class);
        intent.putExtra("page",mData.get(0).getId());
        startActivity(intent);


    }
}
